 /**
 *      Реализация Сервака под NODEJS для курсового проекта
 *       автор: А.А.Семченко ст.гр.702301 ИСИТ
 *      Минск 2012г
 */
/*
var express = require('./mongo/lib/express/express.js')
 , http = require('http')
 , connect = require('./mongo/lib/node_modules/connect');
*/
var express = require('express')

 // подключение к mongodb
//var mongo = require('./mongo/lib/mongodb');
var mongo = require('mongodb');
        var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
        var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : mongo.Connection.DEFAULT_PORT;
        console.log("Connecting to " + host + ":" + port);
//var ObjectID = require('./mongo/lib/mongodb').ObjectID;
var ObjectID = require('mongodb').ObjectID;
        
var db = new mongo.Db('node-mongo-examples', new mongo.Server(host, port, {}), {});


var mass_={
	t:[],
	add:function(a){
		this.t.push(a)
	},
	clear:function(){
		this.t=[]
	}
}

db.open(function(err, db){
                
                Item = {
                        size:0,
                        vagon:[],
                        vesgr:[],
                        kodgr:[],
                        esrsn:[],
                        id:[],
                        _id:[],
                        
                        add:function(vagon,vesgr,kodgr,esrsn,id,_id){
                                this.vagon.push(vagon)
                                this.vesgr.push(vesgr)
                                this.kodgr.push(kodgr)
                                this.esrsn.push(esrsn)
                                this.id.push(id)
                                this._id.push(_id)
                                this.size++
                        },
                        clear:function(){
                                this.vagon=[]
                                this.vesgr=[]
                                this.kodgr=[]
                                this.esrsn=[]
                                this.id=[]
                                this._id=[]
                                this.size=0
                        }
                }
    var user_info={
		user:'',
		role:'',
		add:function(user,role){
			this.user=user;
			this.role=role;
		},
		clear:function(){
			this.user='';
			this.role='';
		}
	} 
	 
                var app = express.createServer();

var DEBAG_LOGGIN=0; // проверка залогиневшегося пользователя

app.get('/', function(req, res){
	if(DEBAG_LOGGIN==0){
		res.sendfile(__dirname + '/html/index.html');
	}
	else
		//res.redirect('/select'); 
	res.send('Request:<br/>'+req.query.a+' + '+req.query.s);
});
				
				app.get('/login', function(req, res){
					    user_info.clear();
					    db.collection('users', function(err, collection) {
						    collection.find({user:req.query.user+'',pass:req.query.pass+''},function(err, cursor) {
                                		cursor.toArray(function(err, items) {
											if(items.length!=0){
												user_info.add(items[0].user,items[0].role)
												res.send(JSON.stringify(user_info))  
											}else 	res.send(JSON.stringify(user_info))  
										});
						    });
						})
				})
				
                app.get('/:id', function(req, res){
				t=req.params.id
			//	console.log(t.toString().indexOf('.js'))
					if(t.toString().indexOf('.js')>0)
						res.sendfile(__dirname + '/js/'+req.params.id);
						else
					res.sendfile(__dirname + '/html/'+req.params.id);
				})
				
			app.get('/bootstrap/css/:id', function(req, res){
				res.sendfile(__dirname + '\\bootstrap\\css\\'+req.params.id);
			})
			
			app.get('/bootstrap/js/:id', function(req, res){
					res.sendfile(__dirname + '\\bootstrap\\js\\'+req.params.id);
			})
			app.get('/img/:id', function(req, res){
				res.sendfile(__dirname + '\\img\\'+req.params.id);
			})	
				
				
                app.get('/select/:vagon?', function(req, res){
					vagon = req.params.vagon
					if(vagon!='all'){
							console.log('>'+vagon)
							db.collection('test', function(err, collection) {
									collection.find({ $or : [ { vagon:req.params.vagon*1 } , { vagon:req.params.vagon} ] },function(err, cursor) {
											cursor.toArray(function(err, items) {
													Item.clear();
													for (i=0;i<items.length;i++)
															Item.add(	items[i].vagon,items[i].vesgr,
																		items[i].kodgr,items[i].esrsn,
																		items[i].id,items[i]._id
																	)
													res.send(JSON.stringify(Item))  
											});
									})//.sort({date:-1});
							})
					}
					else{
					  	db.collection('test', function(err, collection) {
							collection.find({},function(err, cursor) {
								cursor.toArray(function(err, items) {
									res.send(JSON.stringify(items))  
								})
							})	
						})
						
					}
				});     
                
			
				
				
                app.get('/test/:id', function(req, res){
					mass_.clear()
					var reg = /^2/
					console.time('Total_time');
					db.collection('test', function(err, collection) {
							collection.count({nv:/^0/},function(err, count) {
								mass_.add(count)
								
								collection.count({nv:/^1/},function(err, count) {
									mass_.add(count)
									
									collection.count({nv:/^2/},function(err, count) {
										mass_.add(count)
										
										collection.count({nv:/^3/},function(err, count) {
											mass_.add(count)
											
											collection.count({nv:/^4/},function(err, count) {
												mass_.add(count)
												
												collection.count({nv:/^5/},function(err, count) {
													mass_.add(count)
													
													collection.count({nv:/^6/},function(err, count) {
														mass_.add(count)
														
														collection.count({nv:/^7/},function(err, count) {
															mass_.add(count)
															
															collection.count({nv:/^8/},function(err, count) {
																mass_.add(count)
																
																collection.count({nv:/^9/},function(err, count) {
																	mass_.add(count)
																	res.send(JSON.stringify(mass_))
																});
																
															});
														});
															
													});
													
												});
											});
											
										});
										
									});
								});
								
							});
						//res.send(JSON.stringify(mass_))
					})
					console.timeEnd('Total_time');
					
								
                });
                
               
                
                app.get('/insert/:id', function(req, res){
                //      {"vagon":88888888,"vesgr":75,"kodgr":12345,"esrsn":150000}
						res.send('Запись в БД'+req.params.id);
                                obj = JSON.parse(req.params.id)
								
								
								db.collection('test', function(err, collection) {
									collection.find({nv:obj.nv},function(err, cursor) {
											cursor.toArray(function(err, items) {
												if(items.length>=1){
													//update
													console.log(items.length)
													collection.update({nv:obj.nv},{$set:{mgr:obj.mgr,kgr:obj.kgr, esr:obj.esr,ks:obj.ks,kgrp:obj.kgrp,prim:obj.prim,id:0,date:new Date()}},false,true)
												}
												else{
													db.collection('test', function(err, collection) {
														collection.insert({nv:obj.nv, mgr:obj.mgr, kgr:obj.kgr, esr:obj.esr,ks:obj.ks,kgrp:obj.kgrp,prim:obj.prim,id:0,date:new Date()});
													});
												}
											});
									})
								})
								
								
								/*
                                db.collection('test', function(err, collection) {
                                        collection.insert({nv:obj.nv, mgr:obj.mgr, kgr:obj.kgr, esr:obj.esr,ks:obj.ks,kgrp:obj.kgrp,prim:obj.prim,id:0,date:new Date()});
                                });
								*/
                });
				
				
                /*
                app.get('/delete/all', function(req, res){
                        db.collection('test', function(err, collection) {
                                collection.remove({}, function(err, collection) {
                                        res.redirect('/select');                                        
                                })
                                
                        });
                });     
                */
                app.get('/delete/:id', function(req, res){
                        db.collection('test', function(err, collection) {
                        var idString = req.params.id;
                                collection.remove({_id:new ObjectID(req.params.id)}, function(err, collection) {
                                        res.send('Запись с ID='+req.params.id+' удалена')       
                                })
                                
                        });
                });
        
                app.listen(3001);
                console.log('listening on port 3001');
})